(function() {
    'use strict';

    /**
     * @ngdoc function
     * @name webApp.controller:AuthCtrl
     * @description
     * # AuthCtrl
     * Controller of the webApp
     */
    angular.module('webApp')
        .controller('AuthCtrl', AuthCtrl);

    AuthCtrl.$inject = ['$scope', '$rootScope', '$state', 'dataService', '$location', 'helper', '$timeout'];

    function AuthCtrl($scope, $rootScope, $state, dataService, $location, helper, $timeout) {
        $scope.regAction = function() {
            var userType = $location.search().type;
            $timeout(function() {
                loadingToggle(true);
                $scope.userType = userType == "1" ? 1 : 2;
                $scope.adminName = "admin";
                $scope.adminPwd1 = $scope.adminPwd2 = "778899";
                $rootScope.$broadcast("event:close_login_win");
            }, 1000);
        }

        $scope.reg = function() {
            if (!$scope.userType || !$scope.adminName || !$scope.adminPwd1 || !$scope.adminPwd2) {
                helper.myAlert("please complete input!");
            } else if ($scope.adminPwd1 !== $scope.adminPwd2) {
                helper.myAlert("different password");
            } else {
                if ($scope.userType == 1) {
                    dataService.supplierRegister({
                        user_name: $scope.adminName,
                        password: $scope.adminPwd1,
                        password_confirm: $scope.adminPwd2,
                    }).then(function(result) {
                        if (result && result.user_id) {
                            $state.go("main");
                            $rootScope.$broadcast('event:auth-loginRequired');
                        } else {
                            helper.myAlert(result);
                        }
                    });
                }

                if ($scope.userType == 2) {
                    dataService.sellerRegister({
                        user_name: $scope.adminName,
                        password: $scope.adminPwd1,
                        password_confirm: $scope.adminPwd2,
                    }).then(function(result) {
                        if (result && result.partner_id) {
                            $state.go("main");
                            $rootScope.$broadcast('event:auth-loginRequired');
                        } else {
                            helper.myAlert(result);
                        }
                    });
                }

            }
        }
    }
})();
